<template>
  <div class="course-page">
    <!-- 页面标题区域 -->
    <div class="category-nav">
      <div class="nav-header">
        <h2 class="category-title">课程中心</h2>
      </div>
      <div class="nav-content">
        <div class="nav-tags-wrapper">
          <div class="nav-tags">
            <div v-for="category in categories" :key="category.value" class="tag-item"
              :class="{ active: currentCategory === category.label }" @click="handleCategoryClick(category.label)">
              {{ category.label }}
            </div>
          </div>
          <!-- 搜索框区域 -->
          <div class="search-container">
            <el-input v-model="searchKeyword" placeholder="搜索课程..." :prefix-icon="Search" clearable
              class="search-input" />
          </div>
        </div>
      </div>
    </div>

    <!-- 课程列表区域 -->
    <div class="course-container" v-loading="loading">
      <div class="course-grid">
        <div v-for="course in pagedCourses" :key="course.id" class="course-card"
          :class="{ enrolled: course.isRegistered }" @click="$router.push(`/course/${course.id}`)">
          <div class="course-info">
            <h4 class="course-name">{{ course.title }}</h4>
            <p class="course-desc">{{ course.description }}</p>

            <div class="teacher-info">
              <el-avatar :size="42" :src="course.teacherAvatar"></el-avatar>
              <div class="teacher-detail">
                <span class="teacher-name">{{ course.teacher }}</span>
                <span class="teacher-title">{{ course.teacherTitle || '资深讲师' }}</span>
              </div>
            </div>

            <div class="course-meta">
              <div class="meta-item">
                <el-icon>
                  <Calendar />
                </el-icon>
                <span>{{ course.schedule }}</span>
              </div>
            </div>

            <div class="course-action">
              <el-button v-if="!course.isRegistered" type="primary" size="small" @click.stop="handleEnroll(course.id)">
                立即报名
              </el-button>
              <div v-else class="enrolled-status">
                <el-icon class="success-icon">
                  <Check />
                </el-icon>
                <span class="enrolled-text">已报名</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
          :current-page="currentPage" @current-change="handlePageChange" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.course-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.category-nav {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.category-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.nav-tags-wrapper {
  position: relative;
}

.nav-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
}

.tag-item {
  padding: 10px 20px;
  border-radius: 25px;
  background: #fff;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.tag-item:hover {
  color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.tag-item.active {
  background: var(--el-color-primary);
  color: #fff;
  border-color: var(--el-color-primary);
}

.search-container {
  margin-top: 20px;
}

.search-input {
  width: 300px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.course-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 30px;
  margin-bottom: 30px;
}

.course-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #ebeef5;
  cursor: pointer;
  position: relative;
}

.course-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.12);
  border-color: var(--el-color-primary-light-7);
}

.course-info {
  padding: 24px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.course-name {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.course-desc {
  font-size: 14px;
  color: #5c6b7f;
  line-height: 1.6;
  margin-bottom: 20px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  flex-grow: 1;
}

.teacher-info {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 16px 0;
  border-top: 1px dashed rgba(0, 0, 0, 0.08);
  border-bottom: 1px dashed rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.teacher-detail {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.teacher-name {
  font-size: 15px;
  color: #2c3e50;
  font-weight: 500;
}

.teacher-title {
  font-size: 13px;
  color: #8492a6;
}

.course-meta {
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #5c6b7f;
  font-size: 14px;
}

.meta-item .el-icon {
  font-size: 16px;
  color: var(--el-color-primary);
}

.course-action {
  display: flex;
  justify-content: center;
  margin-top: auto;
}

.course-action .el-button {
  width: 100%;
  height: 40px;
  font-size: 15px;
  font-weight: 500;
  border-radius: 10px;
}

.enrolled-status {
  display: flex;
  align-items: center;
  gap: 10px;
  color: var(--el-color-success);
  font-size: 15px;
  background: var(--el-color-success-light-9);
  padding: 10px 16px;
  border-radius: 10px;
  width: 100%;
  justify-content: center;
}

.success-icon {
  background: var(--el-color-success);
  color: white;
  border-radius: 50%;
  padding: 4px;
  font-size: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .course-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .course-info {
    padding: 20px;
  }

  .course-name {
    font-size: 18px;
  }

  .enrolled-status {
    padding: 8px 12px;
    font-size: 14px;
  }

  .nav-tags {
    overflow-x: auto;
    flex-wrap: nowrap;
    padding-bottom: 10px;
  }

  .tag-item {
    flex-shrink: 0;
  }

  .search-container {
    width: 100%;
  }

  .search-input {
    width: 100%;
  }
}
</style>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { getCoursesWithRegistration, enrollCourse } from '@/api/courses'
import { ElMessage } from 'element-plus'
import { Reading, User, Calendar, Timer, Check, Search } from '@element-plus/icons-vue'

const loading = ref(false)
const searchKeyword = ref('')
const currentCategory = ref('全部课程')
const currentPage = ref(1)
const pageSize = ref(12)
const courses = ref([])

// 分类选项
const categories = [
  { label: '全部课程', value: 'all' },
  { label: '健康管理', value: 'health', keywords: ['健康', '养生', '保健', '医疗'] },
  { label: '营养调理', value: 'nutrition', keywords: ['营养', '饮食', '调理', '食疗'] },
  { label: '康复训练', value: 'rehab', keywords: ['康复', '训练', '理疗', '恢复'] },
  { label: '心理关怀', value: 'psychology', keywords: ['心理', '情绪', '辅导', '关怀'] }
]

// 筛选后的课程列表
const filteredCourses = computed(() => {
  let filtered = courses.value

  // 按分类筛选
  if (currentCategory.value !== '全部课程') {
    const category = categories.find(cat => cat.label === currentCategory.value)
    if (category) {
      filtered = filtered.filter(course => {
        const searchText = [
          course.title || '',
          course.description || '',
          course.type || '',
          course.category || ''
        ].join(' ').toLowerCase()
        return category.keywords.some(keyword => searchText.includes(keyword))
      })
    }
  }

  // 按搜索关键词筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase().trim()
    filtered = filtered.filter(course => {
      return course.title?.toLowerCase().includes(keyword) ||
        course.description?.toLowerCase().includes(keyword) ||
        course.teacher?.toLowerCase().includes(keyword)
    })
  }

  return filtered
})

const total = computed(() => filteredCourses.value.length)

const pagedCourses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredCourses.value.slice(start, end)
})

const handlePageChange = (page) => {
  currentPage.value = page
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handleCategoryClick = (category) => {
  currentCategory.value = category
  currentPage.value = 1
}

watch(searchKeyword, () => {
  currentPage.value = 1
})

const handleEnroll = async (courseId) => {
  const course = courses.value.find((c) => c.id === courseId)
  if (course?.isRegistered) {
    ElMessage.warning('您已经报名过该课程')
    return
  }

  try {
    await enrollCourse(courseId)
    const course = courses.value.find((c) => c.id === courseId)
    if (course) {
      course.isRegistered = true
    }
    ElMessage.success('课程报名成功')
  } catch (error) {
    console.error('课程报名失败:', error)
    ElMessage.error(error.response?.data?.message || '课程报名失败')
  }
}

onMounted(() => {
  loading.value = true
  getCoursesWithRegistration()
    .then(response => {
      courses.value = response.data
    })
    .catch(error => {
      console.error('获取课程列表失败:', error)
      ElMessage.error('获取课程列表失败')
    })
    .finally(() => {
      loading.value = false
    })
})
</script>
